﻿/* $RCSFile: CRMLocalizer.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Helpers/CRMLocalizer.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.Helpers
{
 	#region Local TraceSwitch 
	public class CrmLocalizerTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("CrmLocalizerTrace","Special Trace Switch for CrmLocalizerTrace");
	}
	#endregion Local TraceSwitch 


    #region Utilities classes
    
    public class CRMLocFieldDesc : ICloneable
    {
	    int _FieldId;
        int _PortalId;
        string _TypeName                    =   string.Empty;
        string _Fieldname                   =   string.Empty;
        string _DisplayName                 =   string.Empty;
        AttributeInternalType _FieldType    =    AttributeInternalType.String;
        int _FieldFlags;
        int _FieldLenght;
        int _DisplaySize;

        public int FieldId
        {
            get
            {
                return _FieldId;
            }
            set
            {
                _FieldId   =   value;
            }
        }
        public int PortalId
        {
            get
            {
                return _PortalId;
            }
            set
            {
                _PortalId   =   value;
            }
        }
        
        public string TypeName
        {
            get
            {
                return _TypeName;
            }
            set
            {
                _TypeName   =   value;
            }
        }

        public  string Fieldname
        {
            get
            {
                return _Fieldname;
            }
            set
            {
                _Fieldname  =   value;
            }
        }
        
        public  string DisplayName
        {
            get
            {
                return _DisplayName;
            }
            set
            {
                _DisplayName  =   value;
            }
        }

        public AttributeInternalType FieldType
        {
            get
            {
                return _FieldType;
            }
            set
            {
                _FieldType  =   value;
            }
        }
        public InternalDisplayMasks FieldFlags
        {
            get
            {
                return (InternalDisplayMasks)_FieldFlags;
            }
            set
            {
                _FieldFlags =   (int)value;
            }
        }
        
        public int FieldLenght
        {
            get
            {
                return _FieldLenght;
            }
            set
            {
                _FieldLenght    =   value;
            }
        }
        
        public int DisplaySize
        {
            get
            {
                return _DisplaySize;
            }
            set
            {
                _DisplaySize    =   value;
            }
        }
        /// <summary>
        /// Temporary values, lead to some reset when extraced from cache
        /// </summary>
        public string ShortVal      =   string.Empty;
        public string LongVal       =   string.Empty;
        public bool Exist           =   false;
        

        public CRMLocFieldDesc(int wFieldId,int wPortalId,string wTypeName,string wFieldname,AttributeInternalType wFieldType,int wFieldFlags,int wFieldLenght,int wDisplaySize)
        {
    	    FieldId     =   wFieldId;
            PortalId    =   wPortalId;
            TypeName    =   wTypeName;
            Fieldname   =   wFieldname;
            FieldType   =   wFieldType;
            FieldFlags  =   (InternalDisplayMasks)wFieldFlags;
            FieldLenght =   wFieldLenght;
            DisplaySize =   wDisplaySize;
        }
        public CRMLocFieldDesc()
        {}

        /// <summary>
        /// Copy values and reset ShortVal and LongVal to empty and Exists depending reset flag
        /// </summary>
        public CRMLocFieldDesc Copy(bool reset)
        {
            CRMLocFieldDesc desc    =   new CRMLocFieldDesc(FieldId,PortalId,TypeName,Fieldname,FieldType,(int)FieldFlags,FieldLenght,DisplaySize);
            if ( !reset )
            {
                desc.ShortVal      =   ShortVal;
                desc.LongVal       =   LongVal;
                desc.Exist         =   Exist;
            }
            return desc;
        }
        
        /// <summary>
        /// Reset ShortVal and LongVal to empty and Exists to false
        /// </summary>
        public void Reset()
        {
            ShortVal                =   string.Empty;
            LongVal                 =   string.Empty;
            Exist                   =   false;
        }

        /// <summary>
        /// Copy without reset
        /// </summary>
        public object Clone()
        {
            return Copy(false);
        }
    }

    public class CRMFieldDescListKey : IComparable<CRMFieldDescListKey>
    {
        int _PortalId;
        string _TypeName    =   string.Empty;
        string _Fieldname   =   string.Empty;
        
        public int PortalId
        {
            get
            {
                return _PortalId;
            }
            set
            {
                _PortalId   =   value;
            }
        }

        public string TypeName
        {
            get
            {
                return _TypeName;
            }
            set
            {
                _TypeName   =   value;
            }
        }

        public  string Fieldname
        {
            get
            {
                return _Fieldname;
            }
            set
            {
                _Fieldname  =   value;
            }
        }

        public CRMFieldDescListKey(int p,string t,string f)
        {
            PortalId    =   p;
            TypeName    =   t;
            Fieldname   =   f;
        }

        public int CompareTo(CRMFieldDescListKey o)
        {
            if ( PortalId != o.PortalId )
                return PortalId-o.PortalId;
            if ( !TypeName.Equals(o.TypeName) )
                return TypeName.CompareTo(o.TypeName);
            return Fieldname.CompareTo(o.Fieldname);
        }

    }

    public class CRMFieldDescList : SortedList<CRMFieldDescListKey,CRMLocFieldDesc> 
    {
	
        #region Properties (Portal)

        FieldLocalizerDB fDB                    =   new FieldLocalizerDB();

        private PortalSettings _portalSettings;
	    public PortalSettings portalSettings
	    {
		    get
		    {
			    if(_portalSettings == null)
			    {
				    if ( HttpContext.Current != null )
					    _portalSettings     =   (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
			    }
			    return _portalSettings;
		    }
		    set
		    {
			    _portalSettings = value;
		    }
	    }
	
        #endregion
        
        public CRMFieldDescList()
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMFieldDescList Ctor BEG.",CrmLocalizerTrace.Sw.Info);
        }

        public CRMFieldDescList(string entityName)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList Ctor BEG entityName: {0}.",entityName),CrmLocalizerTrace.Sw.Info);
            ReadDescriptors(entityName);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList Ctor END entityName: {0}.",entityName),CrmLocalizerTrace.Sw.Info);
        }

        public CRMFieldDescList(int PortalID)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList Ctor BEG PortalID: {0}.",PortalID),CrmLocalizerTrace.Sw.Info);
            ReadDescriptors(PortalID);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList Ctor END PortalID: {0}.",PortalID),CrmLocalizerTrace.Sw.Info);
        }

        /// <summary>
        /// Copy Ctor resetting Short and LongValues
        /// </summary>
        public CRMFieldDescList(CRMFieldDescList Lst)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList Ctor BEG Copy Lst.Count: {0}.",Lst.Count),CrmLocalizerTrace.Sw.Info);
            foreach ( CRMFieldDescListKey key in Lst.Keys )
            {
                CRMLocFieldDesc desc        =   Lst[key];
                CRMLocFieldDesc desc2       =   desc.Copy(true);
                Add(key,desc2);
            }
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList Ctor END Count: {0}.",Count),CrmLocalizerTrace.Sw.Info);
        }

        /// <summary>
        /// Do a copy resetting Short and LongValues depending on Reset Flag
        /// </summary>
        public CRMFieldDescList Copy(bool reset)
        {
            CRMFieldDescList Lst            =   new CRMFieldDescList();
            foreach ( CRMFieldDescListKey key in Keys )
            {
                CRMLocFieldDesc desc        =   this[key];
                CRMLocFieldDesc desc2       =   desc.Copy(reset);
                Lst.Add(key,desc2);
            }
            return Lst;
        }
        
        /// <summary>
        /// Reset Short and LongValues in each element
        /// </summary>
        public void Reset()
        {
            foreach ( CRMFieldDescListKey key in Keys )
            {
                this[key].Reset();
            }
        }

        public CRMFieldDescList ReadDescriptors(string entityName)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList ReadDescriptors BEG entityName: {0}.",entityName),CrmLocalizerTrace.Sw.Info);
            Clear();
            SqlDataReader dr                            =   null;
            try
            {
                dr                                      =   fDB.GetFieldLocalizerDescByEntity(portalSettings.PortalID,entityName);
                int portalID                            =   portalSettings.PortalID;
                while ( dr.Read() )
                {
                    int FieldId                         =   (int)dr["FieldId"];
                    string Fieldname                    =   (string)dr["Fieldname"];
                    AttributeInternalType FieldType     =   (AttributeInternalType)(int)dr["FieldType"];
                    int FieldFlags                      =   (int)dr["FieldFlags"];
                    int FieldLenght                     =   (int)dr["FieldLenght"];
                    int DisplaySize                     =   (int)dr["DisplaySize"];
                    Add(new CRMFieldDescListKey(portalID,entityName, Fieldname),new CRMLocFieldDesc(FieldId,portalID,entityName,Fieldname,FieldType,FieldFlags,FieldLenght,DisplaySize));
                    if ( CrmLocalizerTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList ReadDescriptors Fieldname: {0}, FieldId: {1}.",Fieldname,FieldId),CrmLocalizerTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMFieldDescList ReadDescriptors ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr != null ) 
                    dr.Close();
            }
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList ReadDescriptors END count: {0}.",Count),CrmLocalizerTrace.Sw.Info);
            return this;
        }

        public CRMFieldDescList ReadDescriptors(int PortalID)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList ReadDescriptors BEG PortalID: {0}.",PortalID),CrmLocalizerTrace.Sw.Info);
            Clear();
            SqlDataReader dr                            =   null;
            try
            {
                dr                                      =   fDB.GetFieldLocalizerDescByPortal(PortalID);
                while ( dr.Read() )
                {
                    int FieldId                         =   (int)dr["FieldId"];
                    string TypeName                     =   (string)dr["TypeName"];
                    string Fieldname                    =   (string)dr["Fieldname"];
                    AttributeInternalType FieldType     =   (AttributeInternalType)(int)dr["FieldType"];
                    int FieldFlags                      =   (int)dr["FieldFlags"];
                    int FieldLenght                     =   (int)dr["FieldLenght"];
                    int DisplaySize                     =   (int)dr["DisplaySize"];
                    Add(new CRMFieldDescListKey(PortalID,TypeName, Fieldname),new CRMLocFieldDesc(FieldId,PortalID,TypeName,Fieldname,FieldType,FieldFlags,FieldLenght,DisplaySize));
                    if ( CrmLocalizerTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList ReadDescriptors Fieldname: {0}, FieldId: {1}.",Fieldname,FieldId),CrmLocalizerTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMFieldDescList ReadDescriptors ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr != null ) 
                    dr.Close();
            }
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList ReadDescriptors END count: {0}.",Count),CrmLocalizerTrace.Sw.Info);
            return this;
        }

        public static CRMFieldDescList GetDescriptors(string entityName)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList GetDescriptors static BEG entityName: {0}.",entityName),CrmLocalizerTrace.Sw.Info);
            string key              =   string.Format("CRMFieldDescList_{0}",entityName);
            if ( Cache2.Exists(key) )
            {
                CRMFieldDescList Lst    = (CRMFieldDescList)Cache2.Get(key);
                Lst.Reset();
                return Lst;
            }
            CRMFieldDescList lst    =   new CRMFieldDescList(entityName);
            Cache2.InsertLong(key,lst);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList GetDescriptors END created entityName: {0}.",entityName),CrmLocalizerTrace.Sw.Info);
            return lst;
        }

        public static CRMFieldDescList GetDescriptors(int PortalID)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList GetDescriptors static BEG PortalID: {0}.",PortalID),CrmLocalizerTrace.Sw.Info);
            string key              =   string.Format("CRMFieldDescPortalList_{0}",PortalID);
            if ( Cache2.Exists(key) )
            {
                CRMFieldDescList Lst    = (CRMFieldDescList)Cache2.Get(key);
                Lst.Reset();
                return Lst;
            }
            CRMFieldDescList lst    =   new CRMFieldDescList(PortalID);
            Cache2.InsertLong(key,lst);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMFieldDescList GetDescriptors END created PortalID: {0}.",PortalID),CrmLocalizerTrace.Sw.Info);
            return lst;
        }
    }

    #endregion Utilities classes

    /// <summary>
    ///	Used for localization actions.
    /// </summary>
    public class CRMLocalizer
    {
        public CRMFieldDescList Vals    =   null;
        FieldLocalizerDB fDB            =   new FieldLocalizerDB();
 
		#region Properties (Portal)
		private PortalSettings _portalSettings;
        
		/// <summary>
		/// Stores current portal settings 
		/// </summary>
		public PortalSettings portalSettings
		{
			get
			{
				if(_portalSettings == null)
				{
					// Obtain PortalSettings from Current Context
					if ( HttpContext.Current != null )
						_portalSettings     =   (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
				}
				return _portalSettings;
			}
			set
			{
				_portalSettings = value;
			}
		}

        
        /// <summary>
        /// Get the Entity Config to build the attributes table for an entity
        /// </summary>
        public static EntityConfig GetEntityConfig(CRMWrapperBase Wrapper,string entityName)
        {
            EntityConfig _TConfig        =   new EntityConfig(Wrapper,entityName);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine(
                string.Format("[V]CrmFieldLocalizer GetEntityConfig created entityName: {0}, vflag: [{1}], isAdmin: {2}, DisplayMask: [{3}] ",
                new object[] {entityName,_TConfig.entityFlags, true, _TConfig.DisplayMask }),CrmLocalizerTrace.Sw.Info);
            return _TConfig;
        }

        /// <summary>
        /// Create a DataTable which will be filled with all attribute from selected entity to 
        /// </summary>
        public static DataTable CreateAttributesTable()
        {
            DataTable tb    =   new DataTable("Attributes");
            DataColumn c1   =   tb.Columns.Add(CrmStr.strConfSchemaName, typeof(string));
            DataColumn c2   =   tb.Columns.Add(CrmStr.strConfDisplayName, typeof(string));
            DataColumn c3   =   tb.Columns.Add(CrmStr.strConfDisplayMask, typeof(int));
            DataColumn c4   =   tb.Columns.Add(CrmStr.strConfAttributeOf, typeof(string));
            DataColumn c6   =   tb.Columns.Add(CrmStr.strConfType, typeof(string));
            DataColumn c6b  =   tb.Columns.Add(CrmStr.strConfIntType, typeof(int));
            DataColumn c8   =   tb.Columns.Add(CrmStr.strConfIsCustomField, typeof(bool));
            DataColumn c9   =   tb.Columns.Add(CrmStr.strConfDefaultValue, typeof(string)); // this will be the string value of the oject
            DataColumn c10  =   tb.Columns.Add(CrmStr.strConfValidForCreate, typeof(bool));
            DataColumn c11  =   tb.Columns.Add(CrmStr.strConfValidForRead, typeof(bool));
            DataColumn c12  =   tb.Columns.Add(CrmStr.strConfValidForUpdate, typeof(bool));

            tb.PrimaryKey   =   new DataColumn[] { c1 };
            return tb;
        }

        public static DataTable CreateAttributesTable(CRMWrapperBase Wrapper,string  entityName)
        {
            DataTable tb                        =   CreateAttributesTable();
            // reset GetEntityConfig to force reading new entityname
            EntityConfig econf                  =   GetEntityConfig(Wrapper,entityName);
            InternalDisplayMasks validFlag      =   InternalDisplayMasks.None | InternalDisplayMasks.RequiredForGrid |
                        InternalDisplayMasks.ValidForGrid | InternalDisplayMasks.RequiredForForm |
                        InternalDisplayMasks.ValidForForm | InternalDisplayMasks.ValidForAdvancedFind;
            econf.InsertAttributesInTable(tb,validFlag,true,true,false,AttributeInternalType.String);
            econf.InsertAttributesInTable(tb,validFlag,true,true,false,AttributeInternalType.Memo);
            return tb;
        }
        
        #endregion
        
        #region Ctor

        public CRMLocalizer()
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMLocalizer Ctor BEG.",CrmLocalizerTrace.Sw.Info);
            Vals    =   new CRMFieldDescList();
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMLocalizer Ctor END.",CrmLocalizerTrace.Sw.Info);
        }
        
        public CRMLocalizer(string entityName)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer Ctor BEG entityName: {0}.",entityName),CrmLocalizerTrace.Sw.Info);
            Vals    =   CRMFieldDescList.GetDescriptors(entityName);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer Ctor END entityName: {0}, Count: {1}.",entityName,Vals.Count),CrmLocalizerTrace.Sw.Info);
        }

        public CRMLocalizer(int PortalID)
        {
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer Ctor BEG PortalID: {0}.",PortalID),CrmLocalizerTrace.Sw.Info);
            Vals    =   CRMFieldDescList.GetDescriptors(PortalID);
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer Ctor END PortalID: {0}, Count: {1}.",PortalID,Vals.Count),CrmLocalizerTrace.Sw.Info);
        }

        #endregion Ctor

        #region Main methods

        public static void ClearCache(int PortalID,string entityName)
        {
            string key              =   string.Format("CRMFieldDescPortalList_{0}",PortalID);
            Cache2.Remove(key) ;
            key                     =   string.Format("CRMFieldDescList_{0}",entityName);
            if ( string.IsNullOrEmpty(entityName) )
                    Cache2.RemoveAll(key);
            else Cache2.Remove(key);
        }

        /// <summary>
        /// Event handler installed during wrapper creation in PortalSecurity class
        /// </summary>
        public static void DynEntity_DynEntityEvent(DynEntity sender,DynEntityEventArgs e)
        {
		    if ( SecurityTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DynEntity_DynEntityEvent BEG EvType: {0}, Type: {1}.",e.EvType,sender),SecurityTraceSwitch.Sw.Info);
            switch ( e.EvType )
            {
                case DynEntityEventType.Localize:
                DynEntityLocalizeArgs ev    =   (DynEntityLocalizeArgs )e;
                new CRMLocalizer().LocaLize(sender,ev);
                break;

                default:
                return;
            }
        }

        /// <summary>
		/// Find translation for a dynEntity attribute
		/// </summary>
		public void LocaLize(DynEntity currentDyn,DynEntityLocalizeArgs e)
		{
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer LocaLize BEG SchemaName: {0}, PropertyName: {1}.",currentDyn.SchemaName,e.PropertyName),CrmLocalizerTrace.Sw.Info);
            string entityName                       =   currentDyn.SchemaName;
            // Retrieve Crm Object and read DB values
            SqlDataReader dr                        =   null;
            try
            {
                // Get Definitions from desc
                Vals                                =   CRMFieldDescList.GetDescriptors(entityName);
                if ( Vals.Count == 0 )
                {
                    if ( CrmLocalizerTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer LocaLize no descriptors defined entityName: '{0}'.", entityName),CrmLocalizerTrace.Sw.Info);
                    // Not found we must take Crm value if exists
                    e.GetCrmValue                   =   true;
                    return;
                }
                CRMFieldDescListKey key             =   new CRMFieldDescListKey(portalSettings.PortalID,currentDyn.SchemaName,e.PropertyName);
                if ( !Vals.ContainsKey(key) )
                {
                    if ( CrmLocalizerTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer LocaLize no descriptors defined entityName: '{0}', PropertyName: '{1}'.",entityName,e.PropertyName),CrmLocalizerTrace.Sw.Info);
                    // Not found we must take Crm value if exists
                    e.Found                         =   false;
                    e.GetCrmValue                   =   true;
                    return;
                }
                CRMLocFieldDesc desc                =   Vals[key];
                // Get existing values
                dr                                  =   fDB.GetSingleFieldLocalizerGlobalized(entityName,currentDyn.PrimaryKeyGuidValue,desc.FieldId);
                if ( dr.Read() )
                {
                    if ( desc.FieldType != AttributeInternalType.Memo )
                            e.LocalizedValue        =   (dr["ShortValue"] == DBNull.Value) ? string.Empty:(string)dr["ShortValue"];
                    else    e.LocalizedValue        =   (dr["LongValue"] == DBNull.Value) ? string.Empty:(string)dr["LongValue"];
                    e.Found                         =   !string.IsNullOrEmpty(e.LocalizedValue);
                    e.GetCrmValue                   =   !e.Found;
                    if ( CrmLocalizerTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer LocaLize found property: '{0}', val: {1}", e.PropertyName,e.LocalizedValue),CrmLocalizerTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMLocalizer LocaLize ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr != null ) 
                    dr.Close();
            }
            if ( CrmLocalizerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMLocalizer LocaLize END found: {0}.",e.Found),CrmLocalizerTrace.Sw.Info);
		}

        #endregion Main methods

    }
}